import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_gallery_saver_plus/image_gallery_saver_plus.dart';
import 'package:openim_common/openim_common.dart';

class FileDetailPage extends StatefulWidget {
  const FileDetailPage({
    Key? key,
    required this.message,
  }) : super(key: key);

  final Message message;

  @override
  State<FileDetailPage> createState() => _FileDetailPageState();
}

class _FileDetailPageState extends State<FileDetailPage> {
  FileElem? get _fileElem => widget.message.fileElem;
  
  bool _isSaving = false;

  @override
  Widget build(BuildContext context) {
    final fileName = _fileElem?.fileName ?? '未知文件';
    final fileSize = _formatFileSize(_fileElem?.fileSize ?? 0);
    
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.black),
          onPressed: () => Navigator.pop(context),
        ),
        title: Text(
          '文件详情',
          style: TextStyle(
            color: Colors.black,
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: true,
      ),
      body: Padding(
        padding: EdgeInsets.all(20.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            // 文件图标
            Container(
              width: 120.w,
              height: 120.w,
              decoration: BoxDecoration(
                color: Styles.c_0089FF.withOpacity(0.1),
                borderRadius: BorderRadius.circular(20.r),
              ),
              child: Icon(
                _getFileIcon(fileName),
                color: Styles.c_0089FF,
                size: 60.w,
              ),
            ),
            
            30.verticalSpace,
            
            // 文件名称
            Container(
              width: double.infinity,
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.w),
              decoration: BoxDecoration(
                color: Colors.grey[50],
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '文件名称',
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.grey[600],
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  6.verticalSpace,
                  Text(
                    fileName,
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: Colors.black87,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
            ),
            
            16.verticalSpace,
            
            // 文件大小
            Container(
              width: double.infinity,
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.w),
              decoration: BoxDecoration(
                color: Colors.grey[50],
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '文件大小',
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.grey[600],
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  6.verticalSpace,
                  Text(
                    fileSize,
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: Colors.black87,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
            ),
            
            Spacer(),
            
            // 保存按钮
            Container(
              width: double.infinity,
              height: 50.h,
              child: ElevatedButton(
                onPressed: _isSaving ? null : _saveFile,
                style: ElevatedButton.styleFrom(
                  backgroundColor: Styles.c_0089FF,
                  foregroundColor: Colors.white,
                  elevation: 0,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                ),
                child: _isSaving
                    ? Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          SizedBox(
                            width: 20.w,
                            height: 20.w,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                            ),
                          ),
                          12.horizontalSpace,
                          Text(
                            '保存中...',
                            style: TextStyle(
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ],
                      )
                    : Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(Icons.download, size: 20.w),
                          8.horizontalSpace,
                          Text(
                            '保存到本地',
                            style: TextStyle(
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ],
                      ),
              ),
            ),
            
            20.verticalSpace,
          ],
        ),
      ),
    );
  }

  Future<void> _saveFile() async {
    if (_isSaving) return;
    
    setState(() {
      _isSaving = true;
    });

    try {
      final fileElem = widget.message.fileElem;
      if (fileElem == null) {
        IMViews.showToast('文件信息不完整');
        return;
      }

      final sourcePath = fileElem.filePath;
      final url = fileElem.sourceUrl;
      final fileName = fileElem.fileName ?? '未知文件';
      final fileSize = fileElem.fileSize;

      // 生成带时间戳的文件名
      final timestampedFileName = _generateFileNameWithTimestamp(fileName);

      // 检查本地文件是否存在
      bool localFileExists = false;
      if (sourcePath != null && sourcePath.isNotEmpty) {
        localFileExists = await File(sourcePath).exists();
      }

      if (localFileExists) {
        // 本地文件存在，直接保存
        final file = File(sourcePath!);
        if (_isVideoFile(fileName)) {
          // 视频文件使用专门的保存方法
          await _saveVideoFile(file, timestampedFileName);
        } else {
          // 其他文件使用通用保存方法
          await HttpUtil.saveFileToGallerySaver(file, name: timestampedFileName);
        }
        IMViews.showToast('保存成功');
      } else if (url != null && url.isNotEmpty) {
        // 需要从网络下载
        if (_isVideoFile(fileName)) {
          // 网络视频文件使用专门的下载保存方法
          await HttpUtil.saveUrlVideo(
            url,
            onCompletion: () {
              IMViews.showToast('保存成功');
            },
          );
        } else {
          // 其他网络文件
          final name = fileName;
          final cachePath = await IMUtils.createTempFile(dir: 'download', name: name);
          
          await HttpUtil.download(
            url,
            cachePath: cachePath,
            onProgress: (count, total) {
              // 可以在这里更新下载进度
            },
          );
          
          // 下载完成，保存到相册
          await HttpUtil.saveFileToGallerySaver(File(cachePath), name: timestampedFileName);
          IMViews.showToast('保存成功');
        }
      } else {
        IMViews.showToast('无法获取文件');
      }
    } catch (e) {
      IMViews.showToast('保存失败: $e');
    } finally {
      if (mounted) {
        setState(() {
          _isSaving = false;
        });
      }
    }
  }

  Future<void> _saveVideoFile(File file, String fileName) async {
    Permissions.storage(() async {
      try {
        Logger.print('saveVideoFile: ${file.path}, fileName: $fileName');
        
        // 使用 saveFile 方法保存视频文件
        final result = await ImageGallerySaverPlus.saveFile(file.path, name: fileName);
        
        if (result != null) {
          var tips = StrRes.saveSuccessfully;
          if (Platform.isAndroid) {
            final filePath = result['filePath']?.toString() ?? '';
            if (filePath.isNotEmpty) {
              final displayPath = filePath.contains('//') ? filePath.split('//').last : filePath;
              tips = '${StrRes.saveSuccessfully}:$displayPath';
            }
          }
          Logger.print('Video saved successfully: $result');
          IMViews.showToast(tips);
        } else {
          Logger.print('Video save result is null');
          IMViews.showToast('保存失败: 保存结果为空');
        }
      } catch (e) {
        Logger.print('Error saving video: $e');
        IMViews.showToast('保存失败: $e');
      }
    });
  }

  bool _isVideoFile(String fileName) {
    final extension = fileName.toLowerCase().split('.').last;
    return ['mp4', 'avi', 'mov', 'mkv', 'wmv', 'flv', '3gp'].contains(extension);
  }

  String _generateFileNameWithTimestamp(String originalFileName) {
    final now = DateTime.now();
    final timestamp = '${now.year}${now.month.toString().padLeft(2, '0')}${now.day.toString().padLeft(2, '0')}_${now.hour.toString().padLeft(2, '0')}${now.minute.toString().padLeft(2, '0')}${now.second.toString().padLeft(2, '0')}';
    
    final dotIndex = originalFileName.lastIndexOf('.');
    if (dotIndex != -1) {
      final nameWithoutExt = originalFileName.substring(0, dotIndex);
      final extension = originalFileName.substring(dotIndex);
      return '${nameWithoutExt}_$timestamp$extension';
    } else {
      return '${originalFileName}_$timestamp';
    }
  }

  IconData _getFileIcon(String fileName) {
    final extension = fileName.toLowerCase().split('.').last;
    
    switch (extension) {
      case 'pdf':
        return Icons.picture_as_pdf;
      case 'doc':
      case 'docx':
        return Icons.description;
      case 'xls':
      case 'xlsx':
        return Icons.table_chart;
      case 'ppt':
      case 'pptx':
        return Icons.slideshow;
      case 'txt':
        return Icons.text_snippet;
      case 'zip':
      case 'rar':
      case '7z':
        return Icons.archive;
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'gif':
        return Icons.image;
      case 'mp4':
      case 'avi':
      case 'mov':
        return Icons.video_file;
      case 'mp3':
      case 'wav':
      case 'flac':
        return Icons.audio_file;
      default:
        return Icons.insert_drive_file;
    }
  }

  String _formatFileSize(int bytes) {
    if (bytes <= 0) return '0 B';
    
    const suffixes = ['B', 'KB', 'MB', 'GB', 'TB'];
    int i = 0;
    double size = bytes.toDouble();
    
    while (size >= 1024 && i < suffixes.length - 1) {
      size /= 1024;
      i++;
    }
    
    return '${size.toStringAsFixed(size < 10 ? 1 : 0)} ${suffixes[i]}';
  }
}